/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package view;

import controller.Cliente;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import model.ClienteDAO;
import model.TabelaBuscaCliente;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import model.ComparaCPF;
import model.ComparaEndereco;
import model.ComparaNome;
import model.ComparaRG;
import model.ComparaSobrenome;
/**
 *
 * @author Matheus
 */
public class frm_cliente extends javax.swing.JFrame {

    /**
     * Creates new form frm_cliente
     */
    //Cria um novo modelo usando a AbstractTableModel
    private TabelaBuscaCliente modelo = new TabelaBuscaCliente();
    
    public frm_cliente() {
        initComponents();
        this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        //Centraliza a tela
        this.setLocationRelativeTo(null);
        this.setTitle("Banco Internacional de TADS - Cliente");
        //Inicializa o combo de busca
        //cboBuscar 1
        cboBuscar.removeAllItems();
        cboBuscar.addItem("CPF");
        cboBuscar.addItem("RG");
        cboBuscar.addItem("NOME");
        cboBuscar.addItem("SOBRENOME");  
        //Inicializa a tabela
        //Atribui o modelo a tabela  e seta os nomes da coluna  
        tblBuscarCli.setModel(modelo);
        tblBuscarCli.getColumnModel().getColumn(0).setHeaderValue("CPF");
        tblBuscarCli.getColumnModel().getColumn(1).setHeaderValue("RG");
        tblBuscarCli.getColumnModel().getColumn(2).setHeaderValue("NOME");
        tblBuscarCli.getColumnModel().getColumn(3).setHeaderValue("SOBRENOME");
        tblBuscarCli.getColumnModel().getColumn(4).setHeaderValue("ENDEREÇO");
        
        try {
            ClienteDAO clidao = new ClienteDAO();
            List<Cliente> lista = clidao.listarCliente();
            modelo.setListaClientes(lista);
            
            
            //Evento para ordenação quando clicar no nome da coluna
            tblBuscarCli.getTableHeader().addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    try{
                        ClienteDAO clidao = new ClienteDAO();
                        List<Cliente> lista = clidao.listarCliente();
                        int numCol = tblBuscarCli.columnAtPoint(e.getPoint());
                        //Ordena por CPF
                        if(numCol == 0){
                            Collections.sort(lista, new ComparaCPF());
                            modelo.setListaClientes(lista);
                        }
                        //Ordena por RG
                        if(numCol == 1){
                            Collections.sort(lista, new ComparaRG());
                            modelo.setListaClientes(lista);
                        }
                        //Ordena por Nome
                        if (numCol == 2){
                            Collections.sort(lista, new ComparaNome());
                            modelo.setListaClientes(lista);
                        }
                        //Ordena por Sobrenome
                        if (numCol == 3){
                            Collections.sort(lista, new ComparaSobrenome());
                            modelo.setListaClientes(lista);
                        }
                        //Ordena por Endereco
                        if (numCol == 4){
                            Collections.sort(lista, new ComparaEndereco());
                            modelo.setListaClientes(lista);
                        }
                    }catch(Exception ex){
                        Logger.getLogger(frm_cliente.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            });            
        } catch (Exception ex) {
            Logger.getLogger(frm_cliente.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        abaConsCad = new javax.swing.JTabbedPane();
        tabConsultar = new javax.swing.JPanel();
        lblBuscar = new javax.swing.JLabel();
        txtBuscar = new javax.swing.JTextField();
        lblBuscarPor = new javax.swing.JLabel();
        cboBuscar = new javax.swing.JComboBox();
        cmdBuscar = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        tblBuscarCli = new javax.swing.JTable();
        cmdAtualizar = new javax.swing.JButton();
        cmdDeletar = new javax.swing.JButton();
        tabCadastro = new javax.swing.JPanel();
        lblNome = new javax.swing.JLabel();
        lblSobrenome = new javax.swing.JLabel();
        lblRg = new javax.swing.JLabel();
        lblCpf = new javax.swing.JLabel();
        lblEndereco = new javax.swing.JLabel();
        txtNome = new javax.swing.JTextField();
        txtSobrenome = new javax.swing.JTextField();
        txtRg = new javax.swing.JTextField();
        txtCpf = new javax.swing.JTextField();
        txtEndereco = new javax.swing.JTextField();
        cmdCadastrar = new javax.swing.JButton();
        cmdLimpar = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Arial", 1, 24)); // NOI18N
        jLabel1.setText("Cliente");

        lblBuscar.setText("Buscar:");

        lblBuscarPor.setText("Buscar Por:");

        cboBuscar.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cboBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cboBuscarActionPerformed(evt);
            }
        });

        cmdBuscar.setText("Buscar");
        cmdBuscar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                cmdBuscarMouseReleased(evt);
            }
        });

        tblBuscarCli.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tblBuscarCli.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblBuscarCliMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(tblBuscarCli);

        cmdAtualizar.setText("Atualizar");
        cmdAtualizar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                cmdAtualizarMouseReleased(evt);
            }
        });

        cmdDeletar.setText("Deletar");
        cmdDeletar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                cmdDeletarMouseReleased(evt);
            }
        });

        javax.swing.GroupLayout tabConsultarLayout = new javax.swing.GroupLayout(tabConsultar);
        tabConsultar.setLayout(tabConsultarLayout);
        tabConsultarLayout.setHorizontalGroup(
            tabConsultarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(tabConsultarLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(tabConsultarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2)
                    .addGroup(tabConsultarLayout.createSequentialGroup()
                        .addComponent(lblBuscar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 224, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(lblBuscarPor)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cboBuscar, 0, 133, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cmdBuscar))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, tabConsultarLayout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(cmdDeletar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cmdAtualizar)))
                .addContainerGap())
        );
        tabConsultarLayout.setVerticalGroup(
            tabConsultarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(tabConsultarLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(tabConsultarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblBuscar)
                    .addComponent(txtBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblBuscarPor)
                    .addComponent(cboBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cmdBuscar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(tabConsultarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmdAtualizar)
                    .addComponent(cmdDeletar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        abaConsCad.addTab("Consultar", tabConsultar);

        lblNome.setText("Nome:");

        lblSobrenome.setText("Sobrenome:");

        lblRg.setText("RG:");

        lblCpf.setText("CPF:");

        lblEndereco.setText("Endereço:");

        txtNome.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtNomeActionPerformed(evt);
            }
        });

        txtSobrenome.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtSobrenomeActionPerformed(evt);
            }
        });

        txtEndereco.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtEnderecoActionPerformed(evt);
            }
        });

        cmdCadastrar.setText("Salvar");
        cmdCadastrar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                cmdCadastrarMouseReleased(evt);
            }
        });
        cmdCadastrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdCadastrarActionPerformed(evt);
            }
        });

        cmdLimpar.setText("Limpar");
        cmdLimpar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                cmdLimparMouseReleased(evt);
            }
        });
        cmdLimpar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdLimparActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout tabCadastroLayout = new javax.swing.GroupLayout(tabCadastro);
        tabCadastro.setLayout(tabCadastroLayout);
        tabCadastroLayout.setHorizontalGroup(
            tabCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(tabCadastroLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(tabCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, tabCadastroLayout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(cmdLimpar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cmdCadastrar)
                        .addContainerGap())
                    .addGroup(tabCadastroLayout.createSequentialGroup()
                        .addGroup(tabCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblCpf)
                            .addComponent(lblRg))
                        .addGap(49, 49, 49)
                        .addGroup(tabCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtRg, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtCpf, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 321, Short.MAX_VALUE))
                    .addGroup(tabCadastroLayout.createSequentialGroup()
                        .addGroup(tabCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblSobrenome)
                            .addComponent(lblEndereco)
                            .addComponent(lblNome))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(tabCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtEndereco)
                            .addComponent(txtSobrenome)
                            .addComponent(txtNome))
                        .addGap(12, 12, 12))))
        );
        tabCadastroLayout.setVerticalGroup(
            tabCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(tabCadastroLayout.createSequentialGroup()
                .addGap(16, 16, 16)
                .addGroup(tabCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtRg, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblRg))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(tabCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtCpf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblCpf))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(tabCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblNome))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(tabCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblSobrenome)
                    .addComponent(txtSobrenome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(tabCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblEndereco)
                    .addComponent(txtEndereco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(24, 24, 24)
                .addGroup(tabCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmdCadastrar)
                    .addComponent(cmdLimpar))
                .addContainerGap(320, Short.MAX_VALUE))
        );

        abaConsCad.addTab("Cadastro", tabCadastro);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator1)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(abaConsCad))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(abaConsCad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(599, 599, 599)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(7, 7, 7))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(20, 20, 20)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cmdLimparActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdLimparActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_cmdLimparActionPerformed

    private void cmdLimparMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cmdLimparMouseReleased
        Limpar();
        
    }//GEN-LAST:event_cmdLimparMouseReleased

    public void Limpar(){
        //Método para limpar os campos de texto do cadastro
        txtCpf.setText("");
        txtEndereco.setText("");
        txtNome.setText("");
        txtRg.setText("");
        txtSobrenome.setText("");
    }
    
    private void cmdCadastrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdCadastrarActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_cmdCadastrarActionPerformed

    private void txtEnderecoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtEnderecoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtEnderecoActionPerformed

    private void txtSobrenomeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtSobrenomeActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtSobrenomeActionPerformed

    private void txtNomeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtNomeActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtNomeActionPerformed

    private void cboBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cboBuscarActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_cboBuscarActionPerformed

    private void cmdCadastrarMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cmdCadastrarMouseReleased
        // TODO add your handling code here:
        try {
            boolean camposPreenchidos = true;
            if("".equals(txtNome.getText()) || txtNome.getText() == null ){
                camposPreenchidos = false;
            }else if("".equals(txtSobrenome.getText()) || txtSobrenome.getText() ==null){
                camposPreenchidos = false;
            }else if("".equals(txtRg.getText()) || txtRg.getText() == null){
                camposPreenchidos = false;
            }else if("".equals(txtCpf.getText()) || txtCpf.getText() == null){
                camposPreenchidos = false;                
            }else if("".equals(txtEndereco.getText()) || txtEndereco.getText() == null){
                camposPreenchidos = false;
            }
            if(camposPreenchidos){
                ClienteDAO cliDAO = new ClienteDAO();
                String nome = txtNome.getText();
                String sobrenome = txtSobrenome.getText();
                String rg = txtRg.getText();
                String cpf = txtCpf.getText();
                String endereco = txtEndereco.getText();
                Cliente cli = new Cliente(nome, sobrenome, rg, cpf, endereco);
                
                //Busca se o cliente já existe para saber se é atualização ou cadastro
                List<Cliente> lc = cliDAO.busca(cpf, 0);
                int existe = lc.size();
                
                if(existe > 0){
                    //Se o cliente já está cadastrado ele atualiza
                    cliDAO.atualizarCliente(cli);
                    JOptionPane.showMessageDialog(null, "Cliente alterado com sucesso!", "Operação Concluída", JOptionPane.INFORMATION_MESSAGE); 
                }
                else{
                    //Se o cliente não estiver cadastrado ele cadastra
                    cliDAO.inserirCliente(cli);
                    JOptionPane.showMessageDialog(null, "Cliente cadastrado com sucesso!", "Operação Concluída", JOptionPane.INFORMATION_MESSAGE); 
                }
                // Atualizar a busca assim que cadastrar um cliente
                List<Cliente> lista = cliDAO.listarCliente();
                modelo.setListaClientes(lista);
                Limpar();
            }else{
                JOptionPane.showMessageDialog(null, "Existem campos em branco!","Atenção", JOptionPane.ERROR_MESSAGE); 
            }
        } catch (Exception ex) {
            Logger.getLogger(frm_cliente.class.getName()).log(Level.SEVERE, null, ex);
            //Colocar janela de erro aqui
        }
    }//GEN-LAST:event_cmdCadastrarMouseReleased

    private void cmdBuscarMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cmdBuscarMouseReleased
        // TODO add your handling code here:
        //Pega os parâmetros de busca
        //0 - CPF        
        //1 - RG          
        //2 - NOME           
        //3 - SOBRENOME
        int pBusca = cboBuscar.getSelectedIndex();
        String str = txtBuscar.getText();
        //cria um novo cliente DAO e uma lista para preencher a tabela
        try {            
            ClienteDAO clidao = new ClienteDAO();
            List<Cliente> lista;
            //faz a busca
            lista = clidao.busca(str, pBusca);
            if(lista.isEmpty()){
                JOptionPane.showMessageDialog(null, "A busca retornou 0 registros!", "Não encontrado",JOptionPane.INFORMATION_MESSAGE);
            }else{
                //chama o metodo pra atualizar a tabela
                modelo.setListaClientes(lista);
            }
        } catch (Exception ex) {
            Logger.getLogger(frm_cliente.class.getName()).log(Level.SEVERE, null, ex);
        }        
    }//GEN-LAST:event_cmdBuscarMouseReleased

    private void cmdDeletarMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cmdDeletarMouseReleased
        // TODO add your handling code here:
        try{
            ClienteDAO cliDAO = new ClienteDAO();
            int linha = tblBuscarCli.getSelectedRow();
            Cliente cliente = modelo.getCliente(linha);
            int resposta = JOptionPane.showConfirmDialog(null,"Deseja excluir o cliente '"+cliente.getNome()+" "+cliente.getSobrenome()+"'?\nObs.: A conta também será excluida");
            if(resposta == 0){
                //exclui o cliente
                cliDAO.deletarCliente(cliente.getCpf());
                JOptionPane.showMessageDialog(null,"Cliente excluido com sucesso!");
                
                // Atualizar a busca assim que deletar um cliente
                List<Cliente> lista = cliDAO.listarCliente();
                modelo.setListaClientes(lista);
            }else{
                JOptionPane.showMessageDialog(null,"Exclusão cancelada!");
            }        
        }catch(Exception ex){
            Logger.getLogger(frm_cliente.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_cmdDeletarMouseReleased

    private void tblBuscarCliMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblBuscarCliMouseClicked
        // TODO add your handling code here
    }//GEN-LAST:event_tblBuscarCliMouseClicked

    private void cmdAtualizarMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cmdAtualizarMouseReleased
        // TODO add your handling code here:
        try{
            ClienteDAO cliDAO = new ClienteDAO();
            int linha = tblBuscarCli.getSelectedRow();
            Cliente cliente = modelo.getCliente(linha);
            // Mudar automaticamente para a aba de cadastro
            abaConsCad.setSelectedIndex(1);
            //Preenche os campos da aba de cadastro
            txtCpf.setText(cliente.getCpf());
            txtEndereco.setText(cliente.getEndereco());
            txtNome.setText(cliente.getNome());
            txtSobrenome.setText(cliente.getSobrenome());
            txtRg.setText(cliente.getRg());
        }catch(Exception ex){
            Logger.getLogger(frm_cliente.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_cmdAtualizarMouseReleased

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(frm_cliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(frm_cliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(frm_cliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(frm_cliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new frm_cliente().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTabbedPane abaConsCad;
    private javax.swing.JComboBox cboBuscar;
    private javax.swing.JButton cmdAtualizar;
    private javax.swing.JButton cmdBuscar;
    private javax.swing.JButton cmdCadastrar;
    private javax.swing.JButton cmdDeletar;
    private javax.swing.JButton cmdLimpar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JLabel lblBuscar;
    private javax.swing.JLabel lblBuscarPor;
    private javax.swing.JLabel lblCpf;
    private javax.swing.JLabel lblEndereco;
    private javax.swing.JLabel lblNome;
    private javax.swing.JLabel lblRg;
    private javax.swing.JLabel lblSobrenome;
    private javax.swing.JPanel tabCadastro;
    private javax.swing.JPanel tabConsultar;
    private javax.swing.JTable tblBuscarCli;
    private javax.swing.JTextField txtBuscar;
    private javax.swing.JTextField txtCpf;
    private javax.swing.JTextField txtEndereco;
    private javax.swing.JTextField txtNome;
    private javax.swing.JTextField txtRg;
    private javax.swing.JTextField txtSobrenome;
    // End of variables declaration//GEN-END:variables
}